package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Resource
    private BrowsingHistoryMapper browsingHistoryMapper;

    @Override

    public IPage<HistoryItemVo> pageItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageItemByUserId(page, userId);
    }

    //根据用户id和房间id保存一条浏览记录
    @Override
    @Async //代表该方法所发送的是一个异步请求
    public void saveHistory(Long userId, Long id) {
        //考虑同一个用户多次游览同一个房间的情况
        /*
        * 不是每次游览都去插入一条新的数据，只在首次游览时插入数据
        * 后续用户查看时，只更新游览时间
        * */
        //1.更加用户id和房间id去数据库当中查询该条记录是否存在
        LambdaQueryWrapper<BrowsingHistory> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(BrowsingHistory::getUserId,userId);
        QueryWrapper.eq(BrowsingHistory::getRoomId,id);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(QueryWrapper);
        //2.如果该条记录不存在，则插入一条新的记录
        if (browsingHistory == null){
            BrowsingHistory browsingHistory1 = new BrowsingHistory(userId, id, new Date());
            browsingHistoryMapper.insert(browsingHistory1);
        }
        //3.如果该条记录存在，则更新该条记录的游览时间
        if (browsingHistory!= null){
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);

        }



    }
}